<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/8/12 15:35
 * Modified Time: 2019/8/12 15:35
 * Version: 2.0
 */

namespace App\Modules\Inventory\Services;


use App\Exceptions\AllValidatorException;
use App\Exceptions\DbException;
use App\Lib\Utilities;
use App\Modules\Inventory\Criterias\GetGoodsCartCriteria;
use App\Modules\Inventory\Repositories\GoodsCartRepository;
use Flower\Core\Repository\Eloquent\BaseService;
use Illuminate\Support\Facades\DB;

class GoodsCartService extends BaseService
{
    protected $goodsCartRepository;

    public function __construct(GoodsCartRepository $goodsCartRepository)
    {
        $this->goodsCartRepository = $goodsCartRepository;
    }

    /**
     * 添加购物车
     * @param $user_id
     * @param $store_id
     * @param $goods_id
     * @param $num
     * @return mixed
     */
    public function addGoodsCart($user_id, $store_id, $goods_id, $num)
    {
        return $this->goodsCartRepository->createGoodsCard($user_id, $store_id, $goods_id, $num);
    }

    /**
     * 获取购物车
     * @param $user_id
     * @param $store_id
     * @param $pageSize
     * @return array
     * @throws \Flower\Core\Repository\Exceptions\RepositoryException
     */
    public function getGoodsCart($user_id, $store_id, $pageSize)
    {
        $data = $this
            ->goodsCartRepository
            ->pushCriteria(new GetGoodsCartCriteria($user_id, $store_id))
            ->paginate($pageSize, ['*']);

        return Utilities::dealPage($data);
    }

    public function delGoodsCart($goods_cart_id)
    {
        DB::beginTransaction();

        try {
            foreach ($goods_cart_id as $key=>$value){
                $this->goodsCartRepository->deleteExistById($value);
            }
            DB::commit();
            return true;
        } catch (\Exception $e){
            DB::rollBack();
            throw new DbException();
        }
    }
}